﻿@using OSBLE.Models.Assignments
@using OSBLE.Areas.AssignmentDetails.ViewModels
@using OSBLE.Models.Courses;
@using OSBLE.Resources
@model AssignmentDetailsViewModel
@{
    ViewBag.Title = "Assignment Details";
    DynamicDictionary headerData = Model.HeaderBuilder.BuildHeader(Model.CurrentAssignment);
    bool HideMail = true;
    if (null == ViewBag.HideMail)
    {
        HideMail = OSBLE.Utility.DBHelper.GetAbstractCourseHideMailValue(ViewBag.ActiveCourseUser.AbstractCourseID);
    }
    else
    {
        HideMail = ViewBag.HideMail;
    }
}
@section AssignmentDetails
{
    <!--No need to pust due date here like other Indexes, as its covered in partial views as InitialFinalPostDueDate-->
    @foreach (string view in Model.HeaderViews)
    {
        string viewLocation = string.Format("HeaderBuilder/{0}", view);
        @Html.Partial(viewLocation, headerData);
    }
}


@section TableData
{
    @if (Model.Client.AbstractRole.CanGrade)
    {

        HashSet<int> sections = new HashSet<int>(); //This hash set is to get all of the sections for this assignment
        HashSet<DiscussionTeam> CrossSectionTeam = new HashSet<DiscussionTeam>();



        var teams = from t in Model.CurrentAssignment.DiscussionTeams
                    orderby t.Team.Name ascending
                    select t;



        foreach (DiscussionTeam assignmentTeam in teams) //This makes the assumption that students in the same group are
        //in the same section
        {
            if (assignmentTeam.Team.TeamMembers.Count > 0)
            {
                sections.Add(assignmentTeam.GetAllTeamMembers()[0].CourseUser.Section);
            }
        }

        List<int> sectionList = new List<int>();

        sectionList.AddRange(sections);

        sectionList.Sort();

        //this bool is to determine whether or not there needs to be a row with a section header.
        bool sectionBool = false;

        //check if all teams are cross section teams.
        bool onlyCross = true;

        //only show sections if there are more than 1 section
        bool showSections = false;

        if (sections.Count > 1)
        {
            showSections = true;
        }

        CourseUser currentUser = ViewBag.ActiveCourseUser;

        //populate cross section teams //create a list of the multiSections
        List<string> multiSections = currentUser.MultiSection != null ? currentUser.MultiSection.Split(',').ToList() : new List<string>();

        //populate cross section teams
        foreach (DiscussionTeam discussionTeam in teams)
        {
            //Make sure all team members are on the same section.
            int temp = -3;
            try
            {
                temp = discussionTeam.Team.TeamMembers.FirstOrDefault().CourseUser.Section;
            }
            catch (Exception)
            {
                temp = -3;
            }
            bool flagCheck;
            bool sectionFlag;
            flagCheck = false;
            sectionFlag = false;

            if (currentUser.Section == -2) //if user in all section, always display users
            {
                sectionFlag = true;
            }

            foreach (TeamMember member in discussionTeam.Team.TeamMembers) //make sure all team members are on the same team.
            {

                //if the current user is a multi section user (not all section)
                if (currentUser.Section == -1)
                {
                    int isInList = multiSections.IndexOf(member.CourseUser.Section.ToString());
                    if (isInList != -1) //if this user's multisection contains this users' section
                    {
                        sectionFlag = true;
                    }
                }

                    //if the current user is a single section user
                else if (currentUser.Section >= 0) //if TA or Instructor is a single section user, check if one of the team members is in their section
                {
                    if (member.CourseUser.Section == currentUser.Section)
                    {
                        sectionFlag = true;
                    }
                }

                //if the teammate we're looking at doesn't have the same section as all others, it's a cross section team
                if (member.CourseUser.Section != temp)
                {
                    flagCheck = true;
                }
            }

            if (flagCheck && sectionFlag) //If the team is cross section and the current user has one member of the team in their section, add it to the list off Cross Sections
            {
                CrossSectionTeam.Add(discussionTeam);
            }
        }

        //after populating the cross section teams

        foreach (int section in sectionList)
        {
            // For TAs, we only want the TA to see students in the section they are in

            if (section < 0)
            {
                continue;
            }

            if (currentUser != null)
            {
                if (currentUser.AbstractRole.Name == "TA") //see if the user is a TA
                {
                    if (currentUser.Section >= 0) //check if the user is a multi-section user or not
                    {
                        if (section != currentUser.Section) //if not, make sure they are in this section before displaying the grades
                        {
                            continue;
                        }
                    }

                    else if (currentUser.Section == -1)
                    {
                        int isInList = multiSections.IndexOf(section.ToString());
                        if (isInList == -1) //if this user's multisection does not contain this section
                        {
                            continue;
                        }
                    }
                }
            }

            sectionBool = false;

            foreach (DiscussionTeam assignmentTeam in teams)
            {

                if (assignmentTeam.GetAllTeamMembers().Count() > 0 && assignmentTeam.GetAllTeamMembers()[0].CourseUser.Section != section)
                {
                    continue;
                }

                //Make sure all team members are on the same section.
                int temp = -3;
                try
                {
                    temp = assignmentTeam.Team.TeamMembers.FirstOrDefault().CourseUser.Section;
                }
                catch (Exception)
                {
                    temp = -3;
                }
                bool flagCheck;

                flagCheck = false;

                foreach (TeamMember member in assignmentTeam.Team.TeamMembers) //make sure all team members are on the same team.
                {
                    if (member.CourseUser.Section != temp)
                    {
                        flagCheck = true;
                        break;
                    }
                }

                if (flagCheck) //If the team is cross section, wait to display later
                {
                    continue;
                }

                if ((!sectionBool) && showSections)
                {
                    <tr class="SectionRow">
                        <th class="Student" colspan="6">
                            Section: @Html.Raw(section)
                        </th>
                    </tr>
                    sectionBool = true;
                }

                //if you reach here, the page is displaying at least one team that is not cross section
                onlyCross = false;

                //end check of cross section team

                if (Model.CurrentAssignment.HasDiscussionTeams)
                {
                    <tr>
                        <th class="TeamHeader" colspan="6">

                            @{string actionLink = Url.Action("CreateTeam", "Mail", new { area = "", teamID = assignmentTeam.Team.ID });
                            }
                            @if (!HideMail)
                            {
                                <a href="@actionLink" title="Email this team">@Helpers.MailButton()</a>
                            }
                            @assignmentTeam.Team.Name -
                            @(Html.ActionLink("View Discussion",
                                "TeacherIndex", "DiscussionAssignment",
                                 new
                                 {
                                     assignmentId = Model.CurrentAssignment.ID,
                                     discussionTeamID = assignmentTeam.ID,
                                     area = ""
                                 }, new { }))

                            @{
                    int newPosts = assignmentTeam.GetNewPostsCount(Model.Client.ID);
                            }
                            @if (newPosts > 0)
                            {
                                @:&nbsp-&nbsp
                                @:@Html.ActionLink("View " + newPosts.ToString() + " Unread Posts",
                                    "TeacherIndex", "DiscussionAssignment",
                                     new
                                     {
                                         assignmentId = Model.CurrentAssignment.ID,
                                         courseUserId = 0,
                                         discussionTeamID = assignmentTeam.ID,
                                         highlightValueString = "NewPosts",
                                         area = ""
                                     }, new { })
                                 }

                            @if (assignmentTeam.Assignment.PreceedingAssignment != null)
                            {
                                if (assignmentTeam.Assignment.PreceedingAssignment.Type == AssignmentTypes.CriticalReview)
                                {
                                    if (assignmentTeam.Assignment.PreceedingAssignment.HasStudentRubric == true)
                                    {
                                        @:&nbsp-&nbsp @Html.ActionLink("View merged rubric",
                                                "ViewForCriticalReview",
                                                "Rubric",
                                                new
                                                {
                                                    assignmentId = assignmentTeam.Assignment.PrecededingAssignmentID,
                                                    authorTeamId = assignmentTeam.AuthorTeamID,
                                                    area = ""
                                                },
                                                new { })
                                    }
                                }
                            }
                            &nbsp-&nbsp
                            @Html.ActionLink("Access reviewed items to discuss",
                         "GetDocumentsForCriticalReviewDiscussion",
                    "FileHandler",
                    new { area = "", discussionTeamID = assignmentTeam.ID },
                    new { onclick = "create_and_open_downloading_submission_dialog()" })
                        </th>
                    </tr>
                }

                var allTeamMembers = (assignmentTeam as DiscussionTeam).GetAllTeamMembers()
                    .OrderBy(t => t.CourseUser.AbstractRoleID, new OSBLE.Models.Courses.CourseRole.CourseRolesInOrder())
                    .ThenBy(t => t.CourseUser.DisplayName((int)CourseRole.CourseRoles.Instructor));

                foreach (TeamMember member in allTeamMembers)
                {
                    //TODO: handle case of multiple teams. we may not have to handle this since users can only be on one discussion team
                    //We are figuring out which INDIVIDUAL assignment team this rubric is tied to so we can display the current
                    //individual user's rubric grade/draft state
                    List<TeamMember> userTeams = member.CourseUser.TeamMemberships.Where(tm => tm.Team.UsedAsAssignmentTeam.Any()).ToList(); //get teams used in an assignment
                    TeamMember tMember = new TeamMember(); //this needs to be a list if we have a case of a user on multiple teams. (wont happen?)
                    foreach (TeamMember rubricTeamMember in userTeams)
                    {
                        List<AssignmentTeam> teamsUsedAsAssignmentTeam = rubricTeamMember.Team.UsedAsAssignmentTeam.ToList();
                        foreach (AssignmentTeam aTeam in teamsUsedAsAssignmentTeam)
                        {
                            if (aTeam.AssignmentID == Model.CurrentAssignment.ID) //we want to grab the team matching this assignment
                            {
                                tMember = rubricTeamMember;
                            }
                        }
                    }

                    DiscussionTeam singleUserAssignmentTeam = new DiscussionTeam();
                    singleUserAssignmentTeam.Team = new Team();
                    singleUserAssignmentTeam.Team.TeamMembers.Add(tMember);
                    singleUserAssignmentTeam.Team.Name = member.CourseUser.DisplayName(Model.Client.AbstractRoleID, false);
                    singleUserAssignmentTeam.TeamID = tMember.TeamID;
                    singleUserAssignmentTeam.Assignment = assignmentTeam.Assignment;
                    singleUserAssignmentTeam.AssignmentID = assignmentTeam.AssignmentID;
                    singleUserAssignmentTeam.ID = (assignmentTeam as DiscussionTeam).ID;

                    <tr>
                        <td>
                            @{string actionLink = Url.Action("CreateUser", "Mail", new { area = "", id = member.CourseUser.UserProfileID });
                            }
                            @if (null != ViewBag.HideMail && !ViewBag.HideMail)
                            {
                                <a href="@actionLink" title="Email this user">@Helpers.MailButton()</a>
                            }
                            @if (member.CourseUser.AbstractRoleID == (int)CourseRole.CourseRoles.TA || member.CourseUser.AbstractRoleID == (int)CourseRole.CourseRoles.Moderator)
                            {
                                @:<span class="TitleText">@member.CourseUser.DisplayNameWithRole(Model.Client.AbstractRoleID, false)</span>
                            }
                            else
                            {
                                if (assignmentTeam.AuthorTeamID == member.TeamID)
                                {
                                    @:(A)
                                }
                                @:@member.CourseUser.DisplayName(Model.Client.AbstractRoleID, false)
                                                            }
                        </td>
                        @foreach (string view in Model.TableColumnHeaders.Keys)
                        {
                            DynamicDictionary tableData = Model.TeamTableBuilders[assignmentTeam].BuildTableForTeam(singleUserAssignmentTeam);
                            string viewLocation = string.Format("TableBuilder/{0}", view);
                            @Html.Partial(viewLocation, tableData);
                        }
                    </tr>
                }
            }
        }


        //if the assignment has teams that are cross section
        if (CrossSectionTeam.Count > 0 && (!onlyCross))
        {
            <tr class="SectionRow">
                <th class="Student" colspan="6">
                    Cross Section Teams:
                </th>
            </tr>
        }

        foreach (DiscussionTeam assignmentTeam in CrossSectionTeam) //make a row for all rows
        {
            if (Model.CurrentAssignment.HasDiscussionTeams)
            {

                <tr>
                    <th class="TeamHeader" colspan="6">

                        @{string actionLink = Url.Action("CreateTeam", "Mail", new { area = "", teamID = assignmentTeam.Team.ID });
                        }
                        @if (null != ViewBag.HideMail && !ViewBag.HideMail)
                        {
                            <a href="@actionLink" title="Email this team">@Helpers.MailButton()</a>
                        }
                        @assignmentTeam.Team.Name -
                        @(Html.ActionLink("View Discussion",
                                "TeacherIndex", "DiscussionAssignment",
                                 new
                                 {
                                     assignmentId = Model.CurrentAssignment.ID,
                                     discussionTeamID = assignmentTeam.ID,
                                     area = ""
                                 }, new { }))

                        @{
                int newPosts = assignmentTeam.GetNewPostsCount(Model.Client.ID);
                        }
                        @if (newPosts > 0)
                        {
                            @:&nbsp-&nbsp
                            @:@Html.ActionLink("View " + newPosts.ToString() + " Unread Posts",
                                    "TeacherIndex", "DiscussionAssignment",
                                     new
                                     {
                                         assignmentId = Model.CurrentAssignment.ID,
                                         courseUserId = 0,
                                         discussionTeamID = assignmentTeam.ID,
                                         highlightValueString = "NewPosts",
                                         area = ""
                                     }, new { })
                                 }

                        @if (assignmentTeam.Assignment.PreceedingAssignment != null)
                        {
                            if (assignmentTeam.Assignment.PreceedingAssignment.Type == AssignmentTypes.CriticalReview)
                            {
                                if (assignmentTeam.Assignment.PreceedingAssignment.HasStudentRubric == true)
                                {
                                    @:&nbsp-&nbsp @Html.ActionLink("View merged rubric",
                                                "ViewForCriticalReview",
                                                "Rubric",
                                                new
                                                {
                                                    assignmentId = assignmentTeam.Assignment.PrecededingAssignmentID,
                                                    authorTeamId = assignmentTeam.AuthorTeamID,
                                                    area = ""
                                                },
                                                new { })
                                    }
                            }
                        }
                        &nbsp-&nbsp
                        @Html.ActionLink("Access reviewed items to discuss",
                         "GetDocumentsForCriticalReviewDiscussion",
                    "FileHandler",
                    new { area = "", discussionTeamID = assignmentTeam.ID },
                    new { onclick = "create_and_open_downloading_submission_dialog()" })
                    </th>
                </tr>
            }

            var allTeamMembers = (assignmentTeam as DiscussionTeam).GetAllTeamMembers()
                .OrderBy(t => t.CourseUser.AbstractRoleID, new OSBLE.Models.Courses.CourseRole.CourseRolesInOrder())
                .ThenBy(t => t.CourseUser.DisplayName((int)CourseRole.CourseRoles.Instructor));

            foreach (TeamMember member in allTeamMembers)
            {
                //TODO: handle case of multiple teams. we may not have to handle this since users can only be on one discussion team
                //We are figuring out which INDIVIDUAL assignment team this rubric is tied to so we can display the current
                //individual user's rubric grade/draft state
                List<TeamMember> userTeams = member.CourseUser.TeamMemberships.Where(tm => tm.Team.UsedAsAssignmentTeam.Any()).ToList(); //get teams used in an assignment
                TeamMember tMember = new TeamMember(); //this needs to be a list if we have a case of a user on multiple teams. (wont happen?)
                foreach (TeamMember rubricTeamMember in userTeams)
                {
                    List<AssignmentTeam> teamsUsedAsAssignmentTeam = rubricTeamMember.Team.UsedAsAssignmentTeam.ToList();
                    foreach (AssignmentTeam aTeam in teamsUsedAsAssignmentTeam)
                    {
                        if (aTeam.AssignmentID == Model.CurrentAssignment.ID) //we want to grab the team matching this assignment
                        {
                            tMember = rubricTeamMember;
                        }
                    }
                }

                DiscussionTeam singleUserAssignmentTeam = new DiscussionTeam();
                singleUserAssignmentTeam.Team = new Team();
                singleUserAssignmentTeam.Team.TeamMembers.Add(tMember);
                singleUserAssignmentTeam.Team.Name = member.CourseUser.DisplayName(Model.Client.AbstractRoleID, false);
                singleUserAssignmentTeam.TeamID = tMember.TeamID;
                singleUserAssignmentTeam.Assignment = assignmentTeam.Assignment;
                singleUserAssignmentTeam.AssignmentID = assignmentTeam.AssignmentID;
                singleUserAssignmentTeam.ID = (assignmentTeam as DiscussionTeam).ID;

                <tr>
                    <td>
                        @{string actionLink = Url.Action("CreateUser", "Mail", new { area = "", id = member.CourseUser.UserProfileID });
                        }
                        @if (null != ViewBag.HideMail && !ViewBag.HideMail)
                        {
                            <a href="@actionLink" title="Email this user">@Helpers.MailButton()</a>
                        }
                        @if (member.CourseUser.AbstractRoleID == (int)CourseRole.CourseRoles.TA || member.CourseUser.AbstractRoleID == (int)CourseRole.CourseRoles.Moderator)
                        {
                            @:<span class="TitleText">@member.CourseUser.DisplayNameWithRole(Model.Client.AbstractRoleID, false)</span>
                            }
                        else
                        {
                            if (assignmentTeam.AuthorTeamID == member.TeamID)
                            {
                                @:(A)
                                }
                                @:@member.CourseUser.DisplayName(Model.Client.AbstractRoleID, false)
                                                            }
                    </td>
                    @foreach (string view in Model.TableColumnHeaders.Keys)
                    {
                        DynamicDictionary tableData = Model.TeamTableBuilders[assignmentTeam].BuildTableForTeam(singleUserAssignmentTeam);
                        string viewLocation = string.Format("TableBuilder/{0}", view);
                        @Html.Partial(viewLocation, tableData);
                    }
                </tr>
            }
        }
    }
}
